package com.scut.chenlujie.library.clink.core;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public abstract class ScheduleJob implements Runnable{
    protected final long idleTimeoutMillisecond;
    protected final Connector connector;
    private volatile Scheduler scheduler;
    private volatile ScheduledFuture scheduledFuture;

    protected ScheduleJob(long idleTime, TimeUnit unit, Connector connector) {
        this.idleTimeoutMillisecond = unit.toMillis(idleTime);
        this.connector = connector;
    }

    //给外部connector调用的
    synchronized void shcedule(Scheduler scheduler){
        this.scheduler = scheduler;
        schedule(idleTimeoutMillisecond);
    }

    synchronized  protected void schedule(long timeoutMillisecond){
        if(scheduler != null){
            scheduledFuture = scheduler.schedule(this,timeoutMillisecond,TimeUnit.MILLISECONDS);
        }
    }

    synchronized protected void unSchedule(){
        if(scheduler != null){
            scheduler = null;
        }
        if(scheduledFuture != null){
            scheduledFuture.cancel(true);
            scheduledFuture = null;
        }
    }
}
